package com.yehun.shiro;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Alan_Xiang
 * 自定义Authenticator
 * 注意，当需要分别定义处理普通用户和管理员验证的Realm时，对应Realm的全类名应该包含字符串“User”，或者“Admin”。
 * 并且，他们不能相互包含，例如，处理普通用户验证的Realm的全类名中不应该包含字符串"Admin"。
 */
public class DefaultModularRealmAuthenticator extends ModularRealmAuthenticator {

    private final static Logger logger = LoggerFactory.getLogger(DefaultModularRealmAuthenticator.class);

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        logger.info("DefaultModularRealmAuthenticator.doAuthenticate, begin...");
        // 强制转换回自定义的CustomizedToken
        UsernamePasswordTypeToken token = (UsernamePasswordTypeToken) authenticationToken;
        logger.info("DefaultModularRealmAuthenticator.doAuthenticate, token={}", token.toString());
        // 登录类型
        ShiroUserType loginType = token.getType();
        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        Collection<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
            logger.info("DefaultModularRealmAuthenticator.doAuthenticate, realm={}", realm.getName());
            if (realm.getName().contains(loginType.getText())) {
                logger.info("DefaultModularRealmAuthenticator.doAuthenticate, is realm={}", realm.getName());
                typeRealms.add(realm);
            }
        }

        logger.info("DefaultModularRealmAuthenticator.doAuthenticate, end...");
        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1) {
            return doSingleRealmAuthentication(typeRealms.iterator().next(), token);
        } else {
            return doMultiRealmAuthentication(typeRealms, token);
        }
    }
}